Skip to main content

DOM Manipulation

Resource

The DOM (or Document Object Model) is a tree-like representation of the contents of a webpage. It represents the structure of the HTML document as a tree structure, with each element, attribute, and text node represented as a node in the tree.

div#container -- parent
├── div.display -- children
└── div.controls -- children

DOM Methods

When your HTML code is parsed by a web browser, it is converted to the DOM. The DOM tree nodes are JavaScript objects that have many properties and methods attached to them. JavaScript provides a set of built-in methods and properties for manipulating the DOM. These properties and methods are the primary tools used to manipulate our webpage.

Manipulating with the DOM is essentially interacting with the in-memory representation of the document that the browser creates based on the original HTML code. → The changes made to the DOM do not directly affect the original HTML file on disk but are reflected in the browser window.

1. Query Selectors

  • element.querySelector(selector) - returns a reference to the first match of selector.
  • element.querySelectorAll(selectors) - returns a “NodeList” containing references to all the matches of the selectors.
    • When using querySelectorAll, the return value is not an array. It looks like an array, and it somewhat acts like an array, but it’s really a “NodeList”.

querySelector() and querySelectorAll() on any element within the document, not just document itself.

<!-- the HTML file -->
<div id="container">
<p class="example">Paragraph 1</p>
<p class="example">Paragraph 2</p>
<p class="another">Paragraph 3</p>
</div>
// index.js
// document represents the entire HTML document
const container = document.querySelector('#container');

// querySelector() called on the container element
// and the querySelectorAll() is called on the entire html document
const firstExampleParagraph = container.querySelector('.example');
const allParagraphs = document.querySelectorAll('p');

2. Create Elements

document.createElement(tagName, [options]): creates a new element of tag type tagName. 

  • [options] in this case means you can add some optional parameters to the function. The createElement() method is a method of the document object, not of individual elements, e.g. container. It's used to create new elements within the document, not within specific elements.
<!-- the HTML file -->
<div id="container">
<p class="example">Paragraph 1</p>
<p class="example">Paragraph 2</p>
<p class="another">Paragraph 3</p>
</div>
// index.js
const div = document.createElement("div");

This function does NOT put your new element into the DOM - it creates it in memory. This is so that you can manipulate the element (by adding styles, classes, ids, text, etc.) before placing it on the page.

You can place the element into the DOM with one of the append elements methods shown below.

3. Append & Remove Elements

1. Append Elements

<!-- the HTML file -->
<div id="container">
<p class="example">Paragraph 1</p>
<p class="example">Paragraph 2</p>
<p class="another">Paragraph 3</p>
</div>
  • parentNode.appendChild(childNode) - appends childNode as the last child of parentNode.
// index.js

// create div element - like shown in createElement()
// childNode
const div = document.createElement("div");

// parentNode
const container = document.querySelector('#container');

// Appends the newly created <div> element as the last child of the container element
container.appendChild(div);
  • parentNode.insertBefore(newNode, referenceNode) - inserts newNode into parentNode before referenceNode.
// parentNode - like shown ealier
const container = document.querySelector('#container');

// newNode
const paragraph = document.createElement("p");

// referenceNode - first example paragraph in the container element
const referenceNode = container.querySelector('.example');

// insert a paragraph into the container before the first example paragraph
container.insertBefore(paragraph, referenceNode)

2. Remove Elements

  • parentNode.removeChild(child) - removes child from parentNode on the DOM and returns a reference to child.
// container is the parentNode
// paragraph is the childNode

// removes the paragraph element from the container
container.removeChild(paragraph);

4. Altering Elements

When you have a reference to an element, you can use that reference to alter the element’s own properties, like:

  • adding inline style information
  • adding/removing/altering attributes
  • changing classes
  • etc.

1. Adding Inline Style

// creates a new <div> referenced in the variable 'div'
const div = document.createElement("div");
// adds the indicated style rule to the element in the div variable
div.style.color = "blue";

// adds several style rules
div.style.cssText = "color: blue; background: white;";

// adds several style rules
div.setAttribute("style", "color: blue; background: white;");
  • When accessing a kebab-case CSS property like background-color with JS, you will need to either use camelCase with dot notation or bracket notation.
// dot notation with kebab case: doesn't work as it attempts to subtract color from div.style.background
// equivalent to: div.style.background - color
div.style.background-color;

// dot notation with camelCase: works, accesses the div's background-color style
div.style.backgroundColor;

// bracket notation with kebab-case: also works
div.style["background-color"];

// bracket notation with camelCase: also works
div.style["backgroundColor"];

2. Editing Attributes

Resource

// if id exists, update it to 'theDiv', else create an id with value "theDiv"
div.setAttribute("id", "theDiv");

// returns value of the specified attribute, in this case "theDiv"
div.getAttribute("id");

// removes specified attribute
div.removeAttribute("id");

3. Working with Classes

// adds class "new" to your new div
div.classList.add("new");

// removes "new" class from div
div.classList.remove("new");

// if div doesn't have class "active" then add it, or if it does, then remove it
div.classList.toggle("active");

→ It is often standard (and cleaner) to define CSS classes containing the desired styles rather than adding and removing inline CSS.

4. Adding Text Content

// creates a text node containing "Hello World!" and inserts it in div
div.textContent = "Hello World!";

5. Adding HTML Content

// renders the HTML inside div
div.innerHTML = "<span>Hello World!</span>";

textContent is preferred over innerHTML for adding text, as innerHTML should be used sparingly to avoid potential security risks.

5. Accessing Element’s Value

It’s just like accessing the value of an object.

<body>
<div>
<label for="item">Enter a new item:</label>
<input type="text" name="item" id="item">
<button>Add item</button>
</body>
const input = document.querySelector("input");
let inputValue = input.value;

6. focus() method

HTMLElement.focus() sets focus on the specified element, this element becomes the active element in the document, ready to receive keyboard and similar events.

In this example, focus() ensures that the cursor automatically jumps back to the input field, making it convenient to continue entering data without needing to manually click or navigate to the next input field.

input.focus()